<template>
  <div class="container_edit">
    <div class="header">
      <p>房源管理>>新增/编辑写字楼</p>
      <el-button
        type="primary"
        @click="back"
      >返回</el-button>
    </div>
    <div class="main">
      <el-form
        :model="params"
        :rules="rules"
        ref="user"
        label-width="150px"
        class=""
      >
        <el-form-item
          label="图片："
          prop="coverKey"
        >
          <el-upload
            class="avatar-uploader"
            :action="upLoadUrl"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="imageUrl"
              :src="imageUrl"
              class="avatar"
            >
            <i
              v-else
              class="el-icon-plus avatar-uploader-icon"
            ></i>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="写字楼名称："
          prop="name"
        >
          <el-input
            v-model="params.name"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="地址："
          prop="detailAddress"
        >
          <el-input
            v-model="params.detailAddress"
            placeholder="请输入"
            id="keyword" type="textbox" @blur="searchKeyword"
          ></el-input>
        </el-form-item>
        <el-form-item
          label=""
          prop=""
        >
          <div id="map_canvas"></div>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="handleSave('user')"
          >保存</el-button>
          <el-button @click="back">返回</el-button>
        </el-form-item>
      </el-form>
    </div>

  </div>
</template>

<script>
  let CONSTANT = require("../../constant/constant.js");
  let common = require("../../common.js");
  var searchService,map,markers = [];
  export default {
    data() {
      return {
        upLoadUrl: "",
        imageUrl: "",
        pageIndex:'',
        params: {
          cityCode: "",
          coverKey: "",
          id: "",
          detailAddress: "",
          latitude: "",
          longitude: "",
          name: "",
        },
        fileList: [],
        rules: {
          coverKey: [
            { required: true, message: "请选择图片", trigger: "blur" }
          ],
          name: [
            { required: true, message: "请输入写字楼名称", trigger: "blur" }
          ],
          detailAddress: [
            { required: true, message: "请输入详细地址", trigger: "blur" }
          ]
        },
      };
    },
    created() {
    },
    mounted() {
      this.id = this.$router.currentRoute.query.id;
      this.pageIndex = this.$router.currentRoute.query.pageIndex||1;
      let sessionId = sessionStorage.getItem("sessionId");
      this.upLoadUrl =
        CONSTANT.URL.SYSTEM.UPLOADFILEBYCOS + "?sessionId=" + sessionId;
      this.init()
      if (this.id) {
        this.getInfo();
      }
    },
    components: {
      "bg-editor": () => import("../common/bg-editor.vue")
    },
    methods: {
      getInfo: function() {
        let url = CONSTANT.URL.BUILDING.detail;
        common.get(url,this.id, res => {
          if (res.status == 200) {
            let data = res.data.bussData;
            this.params = data;
            this.imageUrl = data.coverUrl
            setTimeout( () => {
              this.searchKeyword()
            },1000)
          }
        });
      },
      handleSave: function(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            if(!this.params.latitude || !this.params.longitude) {
              this.$message({
                type: "warning",
                message: "请重新输入检索"
              })
              return false
            }
            this.searchKeyword()
            setTimeout( () => {
              let url = CONSTANT.URL.BUILDING.save;
              common.requestAjax(url, JSON.stringify(this.params), '', res => {
                if (res.status == 200) {
                  this.$message({
                    type: "success",
                    message: "保存成功！"
                  });
                  this.$router.replace('/houseList?pageIndex='+this.pageIndex)
                } else {
                  this.$message({
                    type: "warning",
                    message: res.msg
                  });
                }
              });
            }, 2000)

          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      beforeAvatarUpload(file) {
        this.fileAdd(file)
        console.log(file,'uploadfile')
        // let url = CONSTANT.URL.SYSTEM.UPLOADFILEBYCOS;
        // let param = {
        //   suffix: file.name.split(".")[1], // 文件后缀  png
        //   contentType: file.type // 文件类型  image/png
        // };
        // common.requestAjax(url, '', param, res => {
        //   this.upLoadUrl = res.data.bussData.uploadUrl;
        //   this.params.coverKey = res.data.bussData.fileKey;
        //   common.uploadFile(this.upLoadUrl, file, file.type, res1 => {
        //     this.imageUrl = res.data.bussData.downloadUrl;
        //   })
        // });
      },
      urpChange(file){
        let url = CONSTANT.URL.SYSTEM.UPLOADFILEBYCOS;
        let param = {
          suffix: file.name?file.name.split(".")[1]:'jpeg', // 文件后缀  png
          contentType: file.type // 文件类型  image/png
        };
        common.requestAjax(url, '', param, res => {
          this.upLoadUrl = res.data.bussData.uploadUrl;
          this.params.coverKey = res.data.bussData.fileKey;
          common.uploadFile(this.upLoadUrl, file, file.type, res1 => {
            this.imageUrl = res.data.bussData.downloadUrl;
          })
        });
      },
      fileAdd(file) {
            //判断是否为图片文件
            if (file.type.indexOf('image') == -1) {
                this.$msgbox("请选择图片文件")
            } else {
                let reader = new FileReader();
                let image = new Image();
                let _this = this;
                reader.readAsDataURL(file);
                reader.onload = function () {
                    file.src = this.result;
                    image.onload = function(){
                        let width = image.width;
                        let height = image.height;
                        file.width = width;
                        file.height = height;
                        _this.imgL = file.src  //页面上显示所选择的图片
                    };

                    image.src= file.src; //页面上显示所选择的图片
                    if(file.size/1024 > 1025){  //判断图片的大小，超过1M 进行压缩
                        _this.imgCompress(file,{quality: 0.2})
                    }else{
                        _this.urpChange(file)
                        _this.partitionBase = file.src.split(",")[1]  //这里是因为后台需要 base64和图片type类型两个数据，所以进行了处理
                        _this.imgType ="."+file.type.split("/")[1]
                    }
                }
            }
      },
      //图片压缩
      imgCompress(path,obj){   //path是指上传的图片，obj是压缩的品质，越低越模糊
          let _this = this  //这里的this 是把vue的实例对象指向改变为_this 
          var img = new Image();
          img.src = path.src;
          img.onload = function(){
              var that = this;  //这里的this 是把img的对象指向改变为that 
              // 默认按比例压缩
              var w = that.width,
                  h = that.height,
                  scale = w / h;
              w = obj.width || w;
              h = obj.height || (w / scale);
              var quality = 0.7;  // 默认图片质量为0.7
              //生成canvas
              var canvas = document.createElement('canvas');
              var ctx = canvas.getContext('2d');
              // 创建属性节点
              var anw = document.createAttribute("width");
              anw.nodeValue = w;
              var anh = document.createAttribute("height");
              anh.nodeValue = h;
              canvas.setAttributeNode(anw);
              canvas.setAttributeNode(anh);
              ctx.drawImage(that, 0, 0, w, h);
              // 图像质量
              if(obj.quality && obj.quality <= 1 && obj.quality > 0){
                  quality = obj.quality;
              }
              // quality值越小，所绘制出的图像越模糊
              var base64 = canvas.toDataURL('image/jpeg', quality);
              // 回调函数返回base64的值
              var urlFile = _this.convertBase64UrlToBlob(base64)  //这个地方的处理是为了把压缩的base64转化为对象，获得压缩后图片的大小size，方便对压缩后的图片再次进行判断；
              console.log(urlFile,'urlFileurlFile')
              _this.urpChange(urlFile)
              if(urlFile.size/1024 > 1025){
                  _this.$msgbox("图片过大，请重新上传图片")
              }else{
                  _this.partitionBase = base64.split(",")[1]
                  _this.imgType ="."+urlFile.type.split("/")[1]
              }
          }
      },
      //将base64码转化为file（Blob）
      //此处函数对压缩后的base64经过处理返回{size: "", type: ""} 
      convertBase64UrlToBlob(urlData){
            var arr = urlData.split(','), mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
            while(n--){
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], {type:mime});
      },
      back() {
        this.$router.replace('/houseList?pageIndex='+this.pageIndex)
      },

      init() {
        let self = this
        var center = this.params.latitude && this.params.longitude ? new qq.maps.LatLng(this.params.latitude, this.params.longitude) : new qq.maps.LatLng(39.916527,116.397128);
        map = new qq.maps.Map(document.getElementById('map_canvas'),{
          center: center,
          zoom: 13
        });
//        if (this.params.latitude && this.params.longitude) {
//         var marker = new qq.maps.Marker({
//            map:map,
//          });
//          markers.push(marker);
//          return false
//        }
        var latlngBounds = new qq.maps.LatLngBounds();
        //调用Poi检索类
        searchService = new qq.maps.SearchService({
          pageIndex: 1,
          pageCapacity: 1,
          complete: function(results){
            self.params.latitude = results.detail.pois[0].latLng.lat
            self.params.longitude = results.detail.pois[0].latLng.lng
            console.log(results.detail)
            var pois = results.detail.pois;
            for(var i = 0,l = pois.length;i < l; i++){
              var poi = pois[i];
              latlngBounds.extend(poi.latLng);
              var marker = new qq.maps.Marker({
                map:map,
                position: poi.latLng
              });

              marker.setTitle(i+1);

              markers.push(marker);
            }
            map.fitBounds(latlngBounds);
          },
          error: function(err) {
            console.log(err)
            self.$message({
              type: "warning",
              message: "暂无检索结果，请重新输入"
            })
          }
        });
      },
      clearOverlays(overlays){
        var overlay;
        while(overlay = overlays.pop()){
          overlay.setMap(null);
        }
      },
      searchKeyword(e) {
//        var keyword = document.getElementById("keyword").value;
//        var region = document.getElementById("region").value;
        if (markers.length) {
          this.clearOverlays(markers);
        }
//        searchService.setLocation(region);
        searchService.search(this.params.detailAddress);
      }
    }
  };
</script>
<style lang="scss" scoped>
  #map_canvas {
    width:500px;
    height:500px;
  }
  .table-content {
    width: 500px;
    .table-item {
      position: relative;
      border: 1px solid #dcdfe6;
      i {
        position: absolute;
        right: -30px;
        top: 20px;
        cursor: pointer;
        font-size: 16px;
      }
      &:first-child {
        background-color: #409eff;
        color: #fff;
        border-right: 0px solid #dcdfe6;
        .table-list {
          padding: 0;
        }
      }

      .table-list {
        flex: 2;
        text-align: center;
        padding: 5px 0;
        .el-input {
          height: 70% !important;
          width: 90%;
        }
        &:first-child {
          flex: 3;
          border-right: 1px solid #dcdfe6;
        }
      }
    }
  }
</style>
